extends OrbitComponentBase
class_name OrbitToMouseInDirComponent

@export var sprite:Sprite2D
@export var is_eight_dir:bool

func _orbit(_delta):
	var mouse_pos = get_global_mouse_position()
	var center_to_mouse = mouse_pos - rotation_center.global_position
	var center_to_mouse_dir = (center_to_mouse).normalized()
	var angle_in_radians = center_to_mouse_dir.angle()
	var dir_angle:float
	if is_eight_dir:
		dir_angle = get_eight_dir_angle_from_angle(angle_in_radians)
	else:
		dir_angle = get_four_dir_angle_from_angle(angle_in_radians)
	var offset := Vector2(cos(dir_angle), sin(dir_angle)) * radius
	global_position = rotation_center.global_position + offset
	look_at(global_position + offset)
	if sprite:
		_sprite_flip()

func _sprite_flip():
	if position.x > 0:
		sprite.flip_v = false
	elif position.x < 0:
		sprite.flip_v = true

func get_four_dir_angle_from_angle(angle:float)->float:
	if angle > -PI/4 and angle <= PI/4:
		return 0
	elif angle > PI/4 and angle <= 3*PI/4:
		return PI/2
	elif angle < -PI/4 and angle > -3*PI/4:
		return -PI/2
	else:
		return -PI

func get_eight_dir_angle_from_angle(angle:float)->float:
	if angle > -PI/8 and angle <= PI/8:
		return 0
	elif angle > PI/8 and angle <= 3*PI/8:
		return PI/4
	elif angle > 3*PI/8 and angle <= 5*PI/8:
		return PI/2
	elif angle > 5*PI/8 and angle <= 7*PI/8:
		return 3*PI/4
	elif angle < -PI/8 and angle >= -3*PI/8:
		return -PI/4
	elif angle < -3*PI/8 and angle >= -5*PI/8:
		return -PI/2
	elif angle < -5*PI/8 and angle >= -7*PI/8:
		return -3*PI/4
	else:
		return -PI
